package com.huaxindata.im.main.chat.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxindata.im.R;
import com.huaxindata.im.main.chat.Helper.FileHelper;
import com.huaxindata.im.main.chat.Helper.ImageHelper;
import com.huaxindata.im.main.chat.Helper.LocationHelper;
import com.huaxindata.im.main.chat.Helper.VideoHelper;
import com.huaxindata.im.main.chat.listener.VoicePlayClickListener;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.main.menu.SearchContactActivity;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatStationMessageBody;
import com.huaxindata.im.model.entity.ChatSvgMessageBody;
import com.huaxindata.im.model.entity.ChatSysMessageBody;
import com.huaxindata.im.model.entity.ChatTextMessageBody;
import com.huaxindata.im.model.entity.ChatVoiceMessageBody;
import com.huaxindata.im.model.utils.DateUtils;
import com.huaxindata.im.view.ChatPopWindow;
import com.huaxindata.im.view.TouchLinearLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class ChatAdapter extends BaseAdapter {

    public static final String TIP_1 = "开始聊天吧";
    public static final String TIP_2 = "以上是历史消息";

    private static final int MESSAGE_TYPE_SYSTEM = -1;
    private static final int MESSAGE_TYPE_SENT_TXT = 0;
    private static final int MESSAGE_TYPE_RECV_TXT = 1;
    private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
    private static final int MESSAGE_TYPE_RECV_IMAGE = 3;
    private static final int MESSAGE_TYPE_SENT_LOCATION = 4;
    private static final int MESSAGE_TYPE_RECV_LOCATION = 5;
    private static final int MESSAGE_TYPE_SENT_VOICE = 6;
    private static final int MESSAGE_TYPE_RECV_VOICE = 7;
    private static final int MESSAGE_TYPE_SENT_VIDEO = 8;
    private static final int MESSAGE_TYPE_RECV_VIDEO = 9;
    private static final int MESSAGE_TYPE_SENT_FILE = 10;
    private static final int MESSAGE_TYPE_RECV_FILE = 11;
    private static final int MESSAGE_TYPE_SENT_SVG = 12;
    private static final int MESSAGE_TYPE_RECV_SVG = 13;
    private static final int MESSAGE_TYPE_SENT_STATION = 14;
    private static final int MESSAGE_TYPE_RECV_STATION = 15;
    private static final int MESSAGE_TYPE_SENT_DATAITEM = 16;
    private static final int MESSAGE_TYPE_RECV_DATAITEM = 17;
    private static final int MESSAGE_TYPE_SENT_WORKTASK = 18;
    private static final int MESSAGE_TYPE_RECV_WORKTASK = 19;
    private static final int MESSAGE_TYPE_SENT_WARN = 20;
    private static final int MESSAGE_TYPE_RECV_WARN = 21;

    private static final int MESSAGE_TYPE_COUNT = 22 + 1;

    public static final String clientId =UserManager.getClientId();
    public static final String icon= UserManager.getIconUrl();

    TouchLinearLayout layout;
    ChatPopWindow popWindow;
  //  public static long playMsgId;

    //消息集合
    public ArrayList<ChatMessage> mMessageList = new ArrayList<>();
    private LayoutInflater mInflater;
    private Context mContext;
    private ListView mListView;

    public Contact toChat;//聊天的对象

    public ChatAdapter(Context context, View root, ListView listView, Contact toChat) {
        this.mContext = context;
        layout = (TouchLinearLayout) root;
        mInflater = LayoutInflater.from(context);
        this.mListView = listView;
        this.toChat = toChat;
    }

    public void addMessage(ChatMessage message) {
        //避免同一条消息显示多条记录 时间戳唯一
        for(ChatMessage chatMessage:mMessageList){
            if (message.timestamp==chatMessage.timestamp) {
                return;
            }
        }
        mMessageList.add(message);
    }

    public void addMessage(List<ChatMessage> list) {
        Iterator<ChatMessage> iterator = list.iterator();
        while (iterator.hasNext()) {
            mMessageList.add(0, iterator.next());
        }
    }
    public void clearMessage() {
        mMessageList.clear();
    }
    public int getCount() {
        return mMessageList.size();
    }
    @Override
    public Object getItem(int position) {
        return mMessageList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    /**
     * 获取item类型数量
     */
    public int getViewTypeCount() {
        return MESSAGE_TYPE_COUNT;
    }

    /**
     * 获取item类型
     */
    public int getItemViewType(int position) {
        ChatMessage message = (ChatMessage) getItem(position);
        switch (message.type) {
            case ChatMessageBody.Type.SYSTEM:
                return MESSAGE_TYPE_SYSTEM;
            case ChatMessageBody.Type.WARN:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_WARN;
                } else {
                    return MESSAGE_TYPE_RECV_WARN;
                }
            case ChatMessageBody.Type.WORKTASK:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_WORKTASK;
                } else {
                    return MESSAGE_TYPE_RECV_WORKTASK;
                }
            case ChatMessageBody.Type.TARGET:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_DATAITEM;
                } else {
                    return MESSAGE_TYPE_RECV_DATAITEM;
                }
            case ChatMessageBody.Type.STATION:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_STATION;
                } else {
                    return MESSAGE_TYPE_RECV_STATION;
                }
            case ChatMessageBody.Type.SVG:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_SVG;
                } else {
                    return MESSAGE_TYPE_RECV_SVG;
                }
            case ChatMessageBody.Type.IMAGE:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_IMAGE;
                } else {
                    return MESSAGE_TYPE_RECV_IMAGE;
                }
            case ChatMessageBody.Type.LOCATION:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_LOCATION;
                } else {
                    return MESSAGE_TYPE_RECV_LOCATION;
                }
            case ChatMessageBody.Type.VOICE:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_VOICE;
                } else {
                    return MESSAGE_TYPE_RECV_VOICE;
                }
            case ChatMessageBody.Type.VIDEO:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_VIDEO;
                } else {
                    return MESSAGE_TYPE_RECV_VIDEO;
                }
            case ChatMessageBody.Type.FILE:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_FILE;
                } else {
                    return MESSAGE_TYPE_RECV_FILE;
                }
            default:
                if (clientId.equals(message.sender)) {
                    return MESSAGE_TYPE_SENT_TXT;
                } else {
                    return MESSAGE_TYPE_RECV_TXT;
                }
        }
    }

    /**
     * 创建对应的view
     *
     * @author:guokailin time:2017/6/19 14:39
     */
    public View createViewByMessage(int position, ViewGroup parent) {
        switch (getItemViewType(position)) {
            case MESSAGE_TYPE_SYSTEM:
                return mInflater.inflate(R.layout.row_system_message, parent, false);
            case MESSAGE_TYPE_SENT_TXT:
                return mInflater.inflate(R.layout.row_sent_message, parent, false);
            case MESSAGE_TYPE_RECV_TXT:
                return mInflater.inflate(R.layout.row_received_message, parent, false);
            case MESSAGE_TYPE_SENT_IMAGE:
                return mInflater.inflate(R.layout.row_sent_picture, parent, false);
            case MESSAGE_TYPE_RECV_IMAGE:
                return mInflater.inflate(R.layout.row_received_picture, parent, false);
            case MESSAGE_TYPE_SENT_LOCATION:
                return mInflater.inflate(R.layout.row_sent_location, parent, false);
            case MESSAGE_TYPE_RECV_LOCATION:
                return mInflater.inflate(R.layout.row_received_location, parent, false);
            case MESSAGE_TYPE_SENT_VOICE:
                return mInflater.inflate(R.layout.row_sent_voice, parent, false);
            case MESSAGE_TYPE_RECV_VOICE:
                return mInflater.inflate(R.layout.row_received_voice, parent, false);
            case MESSAGE_TYPE_SENT_VIDEO:
                return mInflater.inflate(R.layout.row_sent_video, parent, false);
            case MESSAGE_TYPE_RECV_VIDEO:
                return mInflater.inflate(R.layout.row_received_video, parent, false);
//            case MESSAGE_TYPE_SENT_FILE:
//                return mInflater.inflate(R.layout.row_sent_file, parent, false);
//            case MESSAGE_TYPE_RECV_FILE:
//                return mInflater.inflate(R.layout.row_received_file, parent, false);
            case MESSAGE_TYPE_SENT_SVG:
                return mInflater.inflate(R.layout.row_sent_svg, parent, false);
            case MESSAGE_TYPE_RECV_SVG:
                return mInflater.inflate(R.layout.row_received_svg, parent, false);
            case MESSAGE_TYPE_SENT_STATION:
                return mInflater.inflate(R.layout.row_sent_station, parent, false);
            case MESSAGE_TYPE_RECV_STATION:
                return mInflater.inflate(R.layout.row_received_station, parent, false);
//            case MESSAGE_TYPE_SENT_DATAITEM:
//                return mInflater.inflate(R.layout.row_sent_dataitem, parent, false);
//            case MESSAGE_TYPE_RECV_DATAITEM:
//                return mInflater.inflate(R.layout.row_received_dataitem, parent, false);
//            case MESSAGE_TYPE_SENT_WORKTASK:
//                return mInflater.inflate(R.layout.row_sent_worktask, parent, false);
//            case MESSAGE_TYPE_RECV_WORKTASK:
//                return mInflater.inflate(R.layout.row_received_worktask, parent, false);
//            case MESSAGE_TYPE_SENT_WARN:
//                return mInflater.inflate(R.layout.row_sent_warn, parent, false);
//            case MESSAGE_TYPE_RECV_WARN:
//                return mInflater.inflate(R.layout.row_received_warn, parent, false);
            default:
                return null;
        }
    }

    /**
     *
     * 待完成：聊天显示对方昵称
     *@author:guokailin
     *time:2017/6/20 14:15
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ChatMessage chatMessage = mMessageList.get(position);
        //将未读消息更新为已读
        if (chatMessage.read==0){
            chatMessage.read=1;
            //更新数据库
            MessageStore.updateReadingState(chatMessage.timestamp, chatMessage.sender, 1);
        }

        ViewHolder viewHolder;
        if (chatMessage.type == ChatMessageBody.Type.SYSTEM) {//系统自动提示消息
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.SYSTEM);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
                if (null==viewHolder||null==viewHolder.mSystemTipTv) {
                    convertView = createViewByMessage(position, parent);
                    viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.SYSTEM);
                }
            }
            ChatSysMessageBody chatSysMessageBody= (ChatSysMessageBody) chatMessage.getMessageBody();
            viewHolder.mSystemTipTv.setText(chatSysMessageBody.getSimpleString(chatSysMessageBody.content));
        } else if (chatMessage.type == ChatMessageBody.Type.TEXT) {//发送的文本消息
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.TEXT);
            } else {
                viewHolder = (ViewHolder) convertView.getTag(ChatMessageBody.Type.TEXT);
                //下面判断是确保文本消息textView得到了初始化，如果一开始是系统消息
                //convertView不空，但是头像并没有初始化就会有空指针异常,以下同理
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.mContentTv) {
                    convertView = createViewByMessage(position, parent);//这一步必须要有
                    viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.TEXT);
                }
            }
            showCommonView(position,chatMessage, viewHolder);//显示头像，进度条，状态等
            ChatTextMessageBody chatTextMessageBody= (ChatTextMessageBody) chatMessage.getMessageBody();
            //显示文字信息
            if (chatTextMessageBody.content !=null){
                Spannable spannableString = Spannable.Factory.getInstance().newSpannable(chatTextMessageBody.content);
                viewHolder.mContentTv.setText(spannableString, TextView.BufferType.SPANNABLE);
            }
            setOnLongClickListener(viewHolder.mContentTv,position);
            viewHolder.mStatusIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    TextHelper.reSendText(hxMessage,ChatAdapter.this);
                }
            });
        } else if (chatMessage.type == ChatMessageBody.Type.VOICE) {//语音消息
          //  final HxFileMessage hxFileMessage= (HxFileMessage) hxMessage;
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.VOICE);
            } else {
                viewHolder = (ViewHolder) convertView.getTag(ChatMessageBody.Type.VOICE);
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.mVoiceImg) {
                    convertView = createViewByMessage(position, parent);
                    viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.VOICE);
                }
            }
            showCommonView(position,chatMessage,viewHolder);//显示基本的view
            //显示语音聊天信息特有的功能
            viewHolder.mVoiceImg.setOnClickListener(new VoicePlayClickListener(chatMessage, viewHolder.mVoiceImg, this, mContext, viewHolder));
            showVoiceView(viewHolder, chatMessage,position);
            viewHolder.mStatusIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (chatMessage.isSender(clientId)) {
                        FileHelper.uploadFileMessage(ChatAdapter.this,chatMessage);
                    } else {
                        FileHelper.downLoadFileMessage(chatMessage,mContext,ChatAdapter.this);
                    }
                }
            });
        } else if (chatMessage.type == ChatMessageBody.Type.IMAGE) {
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.IMAGE);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.mPictureIv) {
                    viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.IMAGE);
                }
            }
            showCommonView(position,chatMessage,viewHolder);
            viewHolder.mPercentTv.setVisibility(View.GONE);
         //   HxFileMessage hxFileMessage= (HxFileMessage) hxMessage;
            ImageHelper.handleImgMessage(mContext,chatMessage,viewHolder,ChatAdapter.this);
            setOnLongClickListener(viewHolder.mPictureIv,position);
        } else if (chatMessage.type == ChatMessageBody.Type.LOCATION) {
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.LOCATION);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.mLocationImgv) {
                    viewHolder = new ViewHolder(convertView,ChatMessageBody.Type.LOCATION);
                }
            }
            showCommonView(position,chatMessage,viewHolder);
           // HxLocationMessage hxLocationMessage= (HxLocationMessage) hxMessage;
            LocationHelper.handleLocationMsg(mContext,ChatAdapter.this,chatMessage,viewHolder);
            setOnLongClickListener(viewHolder.mLocationImgv,position);
        } else if (chatMessage.type == ChatMessageBody.Type.VIDEO) {
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView, ChatMessageBody.Type.VIDEO);
            } else{
                viewHolder= (ViewHolder) convertView.getTag();
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.mVideoThumbnailIv) {
                    viewHolder = new ViewHolder(convertView, ChatMessageBody.Type.VIDEO);
                }
            }
            showCommonView(position,chatMessage,viewHolder);
          //  final HxFileMessage hxFileMessage= (HxFileMessage) hxMessage;
            VideoHelper.handleVideoMsg(mContext,chatMessage,ChatAdapter.this,viewHolder);
            setOnLongClickListener(viewHolder.mVideoLengthTv,position);
        }else if (chatMessage.type==ChatMessageBody.Type.STATION){
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView, ChatMessageBody.Type.STATION);
            } else{
                viewHolder= (ViewHolder) convertView.getTag();
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.deviceName) {
                    viewHolder = new ViewHolder(convertView, ChatMessageBody.Type.STATION);
                }
            }
            showCommonView(position,chatMessage,viewHolder);
            final ChatStationMessageBody stationBody= (ChatStationMessageBody) chatMessage.getMessageBody();
            viewHolder.deviceName.setText(stationBody.name);
            viewHolder.deviceAddress.setText(stationBody.address);
            String flagState;
            switch (stationBody.status) {
                case ChatStationMessageBody.ChatStationStatus.ChatStation_Normal:
                    flagState = "正常";
                    break;
                case ChatStationMessageBody.ChatStationStatus.ChatStation_Timeout:
                    flagState = "超时";
                    break;
                case ChatStationMessageBody.ChatStationStatus.ChatStation_Error:
                    flagState = "故障";
                    break;
                case ChatStationMessageBody.ChatStationStatus.ChatStation_Build:
                    flagState = "建设中";
                    break;
                default:
                    flagState=stationBody.status;
                    break;
            }
            viewHolder.deviceStatus.setText("状态：" + flagState);
            Glide.with(mContext)
                    .asBitmap()
                    .load(stationBody.remotePath)
                    .apply(new RequestOptions().override(Util.getWindowWidth(mContext)/2,Util.getWindowWidth(mContext)/2))
                    .into(viewHolder.deviceImage);
            setOnLongClickListener(viewHolder.rlStation,position);

            viewHolder.rlStation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //跳转到相应的站点
                  //  HxStationInfoActivity.start(mContext,stationBody.code);
                }
            });
        }else if (chatMessage.type == ChatMessageBody.Type.SVG){
            if (convertView == null) {
                convertView = createViewByMessage(position, parent);
                viewHolder = new ViewHolder(convertView, ChatMessageBody.Type.SVG);
            } else{
                viewHolder= (ViewHolder) convertView.getTag();
                if (null==viewHolder||null==viewHolder.mIconIv||null==viewHolder.svgName) {
                    viewHolder = new ViewHolder(convertView, ChatMessageBody.Type.SVG);
                }
            }
            showCommonView(position,chatMessage,viewHolder);
            final ChatSvgMessageBody svgBody= (ChatSvgMessageBody) chatMessage.getMessageBody();
            viewHolder.svgName.setText(svgBody.fileName);
            viewHolder.svgSize.setText(svgBody.SvgSize);
            Glide.with(mContext)
                    .asBitmap()
                    .load(svgBody.remotePath)
                    .apply(new RequestOptions().override(Util.getWindowWidth(mContext)/2,Util.getWindowWidth(mContext)/2))
                    .into(viewHolder.svgImage);
            setOnLongClickListener(viewHolder.rlSvg,position);

            viewHolder.rlSvg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //跳转到相应的svg查看界面
                    //  HxStationInfoActivity.start(mContext,stationBody.code);
                }
            });
        }
        return convertView;
    }

    private void showVoiceView(ViewHolder viewHolder, ChatMessage message,int pos) {
        ChatVoiceMessageBody chatVoiceMessageBody= (ChatVoiceMessageBody) message.getMessageBody();
//        if (ChatAdapter.playMsgId == message.time /*&& VoicePlayClickListener.isPlaying*/) {
        if (chatVoiceMessageBody.isPlay) {
            AnimationDrawable voiceAnimation;
            //针对接收和发送消息的不同设置不同的语音播放图片
            if (!message.isSender(clientId)) { // 接收的消息
                viewHolder.mVoiceImg.setImageResource(R.drawable.voice_from_icon);
            } else {
                viewHolder.mVoiceImg.setImageResource(R.drawable.voice_to_icon);
            }
            voiceAnimation = (AnimationDrawable) viewHolder.mVoiceImg.getDrawable();
            voiceAnimation.start();
        } else {
            if (!message.isSender(clientId)) { // 接收的消息
                viewHolder.mVoiceImg.setImageResource(R.mipmap.chatfrom_voice_playing);
            } else {
                viewHolder.mVoiceImg.setImageResource(R.mipmap.chatto_voice_playing);
            }
        }
        if (!message.isSender(clientId)){//如果是接收的别人发送的语音消息，则需要下载
            if (chatVoiceMessageBody.getLocalPath()==null) {//如果语音文件没有下载下来就去服务器下载
                FileHelper.downLoadFileMessage(message,mContext,this);
            }
        }
        //显示语音秒数
      //  long len=chatVoiceMessageBody.getMediaLength(chatVoiceMessageBody.getLocalPath()) / 1000;
     if (chatVoiceMessageBody.duration/1000 > 0) {
            viewHolder.mVoiceLengthTv.setText(chatVoiceMessageBody.duration/1000 + "\"");
            viewHolder.mVoiceLengthTv.setVisibility(View.VISIBLE);
        } else {
            viewHolder.mVoiceLengthTv.setVisibility(View.INVISIBLE);
        }

        setOnLongClickListener(viewHolder.mVoiceImg,pos);
    }

    /**
    *
    * 显示不同类型的消息的共有的view，比如都有头像，昵称，时间，进度条，状态图片
    *@author:guokailin
    *time:2017/6/30 11:15
    */
    private void showCommonView(int position,ChatMessage message, ViewHolder viewHolder) {
        HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
        //如果是发送者，更新发送状态；如果是接收方则无需处理
      //  Log.e("lwjing","message id"+message.sender+" "+"clientid "+clientId);
        if (message.isSender(clientId)) {
            //根据发送消息的状态来显示ui,若发送成功就刷新适配器
          //  Log.e("lwjing","sender "+clientId+" "+UserManager.getNickName());
            if (message.messageState == ChatMessage.Status.SUCCESS) {// 发送成功
                viewHolder.mProgressBar.setVisibility(View.GONE);
                viewHolder.mStatusIv.setVisibility(View.GONE);
            } else if (message.messageState == ChatMessage.Status.ERROR) {// 发送失败
                viewHolder.mProgressBar.setVisibility(View.GONE);
                viewHolder.mStatusIv.setVisibility(View.VISIBLE);
            } else if (message.messageState == ChatMessage.Status.DOING) {// 发送中或接收中
                viewHolder.mProgressBar.setVisibility(View.VISIBLE);
                viewHolder.mStatusIv.setVisibility(View.GONE);
            }
            viewHolder.mNickNameTv.setVisibility(View.VISIBLE);
           //  Glide.with(mContext).load(icon).into(viewHolder.mIconIv);//显示头像
            instance.setHeadImage(mContext, icon, UserManager.getNickName(), viewHolder.mIconIv);
        } else {
          //  Log.e("lwjing","receive "+" "+toChat.getNickName());
            if (toChat instanceof ContactPerson) {//与好友聊天
                viewHolder.mProgressBar.setVisibility(View.GONE);
                viewHolder.mStatusIv.setVisibility(View.GONE);
                viewHolder.mNickNameTv.setVisibility(View.GONE);
              //  Glide.with(mContext).load(toChat.getIcon()).into(viewHolder.mIconIv);//显示头像
                instance.setHeadImage(mContext, toChat.getIcon(), toChat.getNickName(), viewHolder.mIconIv);
            } else if (toChat instanceof ContactGroup) {//群聊天
                viewHolder.mProgressBar.setVisibility(View.GONE);
                viewHolder.mStatusIv.setVisibility(View.GONE);
                ContactGroup group= (ContactGroup) toChat;
                String id = message.sender;
                String nickName="";//获取发消息的群成员的昵称
                String icon = "";//获取发消息群成员的头像
                if (group.peoples == null){
                    return;
                }
                int size=group.peoples.length;
                for (int i = 0; i < size; i++) {
                    if (id.equals(group.peoples[i])) {
                        nickName=group.nickNames[i];
                        icon=group.icons[i];
                        break;
                    }
                }
                viewHolder.mNickNameTv.setText(nickName);
              //  Glide.with(mContext).load(icon).into(viewHolder.mIconIv);//显示头像
                instance.setHeadImage(mContext, icon, UserManager.getNickName(), viewHolder.mIconIv);
            }
        }
        showTime(position, viewHolder.mTimeTv);
    }

    /**
     *
     * 如果聊天时间间隔大于5分钟则显示聊天时间间隔
     *@author:guokailin
     *time:2017/6/20 14:22
     */
    private void showTime(int position, TextView timeTv) {
        ChatMessage message = (ChatMessage) getItem(position);
        if (position == 0) {
            timeTv.setText(DateUtils.getTimestampString(new Date(message.timestamp),mContext));
            timeTv.setVisibility(View.VISIBLE);
        } else {
            // 两条消息时间离得如果稍长，显示时间
            final ChatMessage prev = (ChatMessage) getItem(position - 1);
            if (prev != null && !DateUtils.isCloseEnough(prev.timestamp, message.timestamp)) {
                timeTv.setText(DateUtils.getTimestampString(new Date(message.timestamp),mContext));
                timeTv.setVisibility(View.VISIBLE);
            } else {
                timeTv.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 刷新适配器，选择滑动到哪个位置
     *
     * @author:guokailin time:2017/6/19 15:11
     */
    public void refreshTo(int position) {
        mListView.setSelection(position);
        notifyDataSetChanged();
    }

    public void refreshToLast() {
        if (mMessageList != null) {
            refreshTo(getCount() - 1);
        }
    }

    public RefreshHandler mHandler = new RefreshHandler(this);
    /**
    *  进行界面刷新的adapter,由于发送文件消息是通过异步发送的，
     *  更新ui的时候采用handler进行子线程和主线程通信
    *@author:guokailin
    *time:2017/6/30 9:51
    */
    public static class RefreshHandler extends Handler{
        public final static int REFRESH_UI=1001;
        public final static int REFRESH_TO_LAST_SELECTION=1002;
        public final static int REFRESH_TO_POSITION=1003;

        WeakReference<ChatAdapter> mWeakReference;
        ChatAdapter mChatAdapter;
        public RefreshHandler(ChatAdapter chatAdapter) {
            super();
            mWeakReference = new WeakReference<>(chatAdapter);
            mChatAdapter=mWeakReference.get();
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_UI:
                    mChatAdapter.notifyDataSetChanged();
                    break;
                case REFRESH_TO_LAST_SELECTION:
                    mChatAdapter.refreshToLast();
                    break;
                case REFRESH_TO_POSITION:
                    int position=msg.arg1;
                    mChatAdapter.refreshTo(position);
                    break;
            }

        }
    }

    /**
     * 长按消息框 支持复制删除转发
     * @param view
     * @param pos
     */
    private void setOnLongClickListener(View view, int pos) {
        view.setTag(R.id.iv_icon, pos);
        view.setOnLongClickListener(longClickListener);
    }

    private final View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (popWindow == null) {
                popWindow = new ChatPopWindow(mContext);
                popWindow.setCallBack(callBack);
            }
            //popWindow.showAsDropDown(v,(v.getWidth()-popWindow.getWidth())/2,-v.getHeight()-popWindow.getHeight());
            popWindow.show(v, layout.touchX, layout.touchY, mMessageList.get((Integer) v.getTag(R.id.iv_icon)));
            return true;
        }
    };

    public boolean isPopWindowShow() {
        return popWindow != null && popWindow.isShowing();
    }

    private final ChatPopWindow.ActionCallBack callBack = new ChatPopWindow.ActionCallBack() {
        @Override
        public void callback(ChatMessage message, int resID) {
            if (resID == R.id.tv_copy) {
                if (message.type == ChatMessageBody.Type.TEXT) {
                    //文本类消息
                    final ClipData clipData = ClipData.newPlainText("message", message.message);
                    ClipboardManager clipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboardManager.setPrimaryClip(clipData);
                    Toast.makeText(mContext, "已复制", Toast.LENGTH_SHORT).show();
                } else {
                    //附件类消息
                    Toast.makeText(mContext, "暂不支持", Toast.LENGTH_SHORT).show();
                }
            } else if (resID == R.id.tv_send) {
                Intent intent = new Intent(mContext, SearchContactActivity.class);
                intent.putExtra("message", message);
//                mContext.startActivityForResult(intent, 1101);
            } else if (resID == R.id.tv_del) {
                //从缓存删除
                mMessageList.remove(message);
                //从数据库删除该条消息
                MessageStore.delete(message.sender, message.timestamp);
                notifyDataSetChanged();
            }
        }
    };

    public static class ViewHolder{
        //几种消息通用的view
        public TextView mNickNameTv;//显示昵称的textView
        public ProgressBar mProgressBar;
        public TextView mTimeTv;//发送的时间间隔长了就显示时间
        public AvatarImageView mIconIv;//头像
        public ImageView mStatusIv;//显示是发送成功还是发送失败时的图片

        //系统提示专用textView
        public TextView mSystemTipTv;
        //文字消息专用的textView
        public TextView mContentTv;//显示消息内容的TextView
        //语音消息专用
        public ImageView mVoiceImg;//显示语音图片的imgview
        public TextView mVoiceLengthTv;//显示语音时间长度的tv
        //图片消息专用
        public ImageView mPictureIv;//显示发送或接收到的图片
        public TextView mPercentTv;//显示发送进度或接收进度的tv
        //位置消息专用
        public ImageView mLocationImgv;
        public TextView mLocationTv;
        //视频消息专用
        public ImageView mVideoThumbnailIv;//视频的缩略图
        public TextView mVideoSizeTv;
        public TextView mVideoLengthTv;
        public ImageButton mVideoPlayBtn;
        //发送站点消息专用
        public TextView deviceName;
        public TextView deviceStatus;
        public TextView deviceAddress;
        public ImageView deviceImage;
        public RelativeLayout rlStation;
        private TextView svgName;
        private TextView svgSize;
        private ImageView svgImage;
        private RelativeLayout rlSvg;

        public ViewHolder(View itemView,int type) {
            itemView.setTag(this);
            initView(itemView,type);
        }
        private void initView(View view,int type) {
            switch (type) {
                case ChatMessageBody.Type.SYSTEM:
                    //文字消息textview初始化
                    mSystemTipTv = (TextView) view.findViewById(R.id.system_tip);
                    break;
                case ChatMessageBody.Type.TEXT:
                    initBaseView(view);
                    //文字消息textview初始化
                    mContentTv = (TextView) view.findViewById(R.id.tv_chat_content);
                    break;
                case ChatMessageBody.Type.VOICE:
                    initBaseView(view);
                    //语音消息初始化
                    mVoiceImg = (ImageView) view.findViewById(R.id.iv_voice);
                    mVoiceLengthTv = (TextView) view.findViewById(R.id.tv_length);
                    break;
                case ChatMessageBody.Type.IMAGE:
                    //图片消息
                    initBaseView(view);
                    mPictureIv = (ImageView) view.findViewById(R.id.iv_sendPicture);
                    mPercentTv = (TextView) view.findViewById(R.id.percentage);
                    break;
                case ChatMessageBody.Type.LOCATION:
                    initBaseView(view);
                    mLocationImgv = (ImageView) view.findViewById(R.id.img_location);
                    mLocationTv = (TextView) view.findViewById(R.id.tv_location);
                    break;
                case ChatMessageBody.Type.VIDEO:
                    initBaseView(view);
                    mVideoThumbnailIv = (ImageView) view.findViewById(R.id.video_thumbnail_iv);
                    mVideoSizeTv = (TextView) view.findViewById(R.id.video_size_tv);
                    mVideoLengthTv = (TextView) view.findViewById(R.id.video_length_tv);
                    mVideoPlayBtn = (ImageButton) view.findViewById(R.id.video_play_btn);
                    break;
                case ChatMessageBody.Type.STATION:
                    initBaseView(view);
                    deviceName= (TextView) view.findViewById(R.id.station_device_name);
                    deviceStatus = (TextView) view.findViewById(R.id.station_device_status);
                    deviceAddress = (TextView) view.findViewById(R.id.station_device_address);
                    deviceImage = (ImageView) view.findViewById(R.id.station_divece_image);
                    rlStation= (RelativeLayout) view.findViewById(R.id.rl_picture);
                    break;
                case ChatMessageBody.Type.SVG:
                    initBaseView(view);
                    svgName= (TextView) view.findViewById(R.id.svg_name);
                    svgSize = (TextView) view.findViewById(R.id.svg_size);
                    svgImage = (ImageView) view.findViewById(R.id.svg_image);
                    rlSvg= (RelativeLayout) view.findViewById(R.id.rl_picture);

                    break;
            }
        }
        /**
        *
        *大部部的消息类型布局都包括5个基本的view,分别是
         * 发送消息的进度条，发送时间，用户头像，发送状态的图片，显示昵称的textview
        *@author:guokailin
        *time:2017/6/30 11:39
        */
        private void initBaseView(View view){
            mProgressBar = (ProgressBar) view.findViewById(R.id.pb_sending);
            mTimeTv = (TextView) view.findViewById(R.id.timestamp);
            mIconIv = (AvatarImageView) view.findViewById(R.id.iv_user_icon);
            mStatusIv = (ImageView) view.findViewById(R.id.iv_status);
            mNickNameTv = (TextView) view.findViewById(R.id.tv_user_nickname);
        }
    }
    /**
    *
    *设置发送失败重新发送消息的监听，不同的消息类型做不同的处理
    *@author:guokailin
    *time:2017/6/30 11:48
    */
    public interface OnResendClickListenner{
        void onClick(ChatMessage message);
    }
}